import React, { useState, useEffect } from 'react';
import {
  Card,
  Descriptions,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  InputNumber,
  message,
  Avatar,
  Tag,
  Tabs,
  Spin
} from 'antd';
import {
  EditOutlined,
  UserOutlined,
  MailOutlined,
  PhoneOutlined,
  HomeOutlined,
  LockOutlined,
  BookOutlined
} from '@ant-design/icons';
import { useAuth } from '../../contexts/AuthContext';
import apiService from '../../services/apiService';
import authService from '../../services/authService';
import moment from 'moment';

const { Option } = Select;
const { TabPane } = Tabs;

const Profile = () => {
  const { user, isAdmin, isTeacher, isStudent } = useAuth();
  const [profileData, setProfileData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [passwordModalVisible, setPasswordModalVisible] = useState(false);
  const [recentBookings, setRecentBookings] = useState([]);
  const [recentCourses, setRecentCourses] = useState([]);
  const [form] = Form.useForm();
  const [passwordForm] = Form.useForm();

  useEffect(() => {
    loadProfileData();
    loadRecentData();
  }, []);

  const loadProfileData = async () => {
    try {
      setLoading(true);
      let data;
      if (isStudent()) {
        data = await apiService.getStudent(user.relatedId);
      } else if (isTeacher()) {
        data = await apiService.getTeacher(user.relatedId);
      } else {
        // 管理员没有关联的学生或教师信息
        data = {
          name: user.username,
          email: user.email,
          role: user.role
        };
      }
      setProfileData(data);
    } catch (error) {
      message.error('加载个人信息失败');
      console.error('加载个人信息失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadRecentData = async () => {
    try {
      if (isStudent()) {
        const bookings = await apiService.getBookingsByStudent(user.relatedId);
        setRecentBookings(bookings.slice(0, 5));
      } else if (isTeacher()) {
        const courses = await apiService.getCoursesByTeacher(user.relatedId);
        setRecentCourses(courses.slice(0, 5));
      }
    } catch (error) {
      console.error('加载最近数据失败:', error);
    }
  };

  const handleEditProfile = () => {
    if (profileData) {
      form.setFieldsValue({
        ...profileData,
        birthDate: profileData.birthDate ? moment(profileData.birthDate) : null,
        hireDate: profileData.hireDate ? moment(profileData.hireDate) : null
      });
    }
    setEditModalVisible(true);
  };

  const handleUpdateProfile = async (values) => {
    try {
      const updateData = {
        ...values,
        birthDate: values.birthDate ? values.birthDate.format('YYYY-MM-DD') : null,
        hireDate: values.hireDate ? values.hireDate.format('YYYY-MM-DD') : null
      };

      if (isStudent()) {
        await apiService.updateStudent(user.relatedId, updateData);
      } else if (isTeacher()) {
        await apiService.updateTeacher(user.relatedId, updateData);
      }

      message.success('个人信息更新成功');
      setEditModalVisible(false);
      loadProfileData();
    } catch (error) {
      message.error('更新失败');
      console.error('更新个人信息失败:', error);
    }
  };

  const handleChangePassword = async (values) => {
    try {
      await authService.updatePassword(
        user.id,
        values.currentPassword,
        values.newPassword
      );
      message.success('密码修改成功');
      setPasswordModalVisible(false);
      passwordForm.resetFields();
    } catch (error) {
      message.error(error.response?.data?.message || '密码修改失败');
      console.error('修改密码失败:', error);
    }
  };

  const getGenderText = (gender) => {
    return gender === 'MALE' ? '男' : '女';
  };

  const getRoleText = (role) => {
    switch (role) {
      case 'ADMIN':
        return '管理员';
      case 'TEACHER':
        return '教师';
      case 'STUDENT':
        return '学生';
      default:
        return role;
    }
  };

  const getRoleColor = (role) => {
    switch (role) {
      case 'ADMIN':
        return 'red';
      case 'TEACHER':
        return 'blue';
      case 'STUDENT':
        return 'green';
      default:
        return 'default';
    }
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'PENDING':
        return 'orange';
      case 'CONFIRMED':
        return 'green';
      case 'CANCELLED':
        return 'red';
      default:
        return 'default';
    }
  };

  const getStatusText = (status) => {
    switch (status) {
      case 'PENDING':
        return '待确认';
      case 'CONFIRMED':
        return '已确认';
      case 'CANCELLED':
        return '已取消';
      default:
        return status;
    }
  };

  if (loading || !profileData) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div>
      <Card
        title={
          <Space>
            <Avatar size={40} icon={<UserOutlined />} />
            个人资料
            <Tag color={getRoleColor(user.role)}>
              {getRoleText(user.role)}
            </Tag>
          </Space>
        }
        extra={
          <Space>
            <Button
              icon={<LockOutlined />}
              onClick={() => setPasswordModalVisible(true)}
            >
              修改密码
            </Button>
            {(isStudent() || isTeacher()) && (
              <Button
                type="primary"
                icon={<EditOutlined />}
                onClick={handleEditProfile}
              >
                编辑资料
              </Button>
            )}
          </Space>
        }
      >
        <Tabs defaultActiveKey="1">
          <TabPane tab="基本信息" key="1">
            <Descriptions bordered column={2}>
              <Descriptions.Item label="用户名" span={1}>
                {user.username}
              </Descriptions.Item>
              <Descriptions.Item label="角色" span={1}>
                <Tag color={getRoleColor(user.role)}>
                  {getRoleText(user.role)}
                </Tag>
              </Descriptions.Item>
              
              {profileData.name && (
                <Descriptions.Item label="姓名" span={1}>
                  <Space>
                    <UserOutlined />
                    {profileData.name}
                  </Space>
                </Descriptions.Item>
              )}
              
              {profileData.gender && (
                <Descriptions.Item label="性别" span={1}>
                  <Tag color={profileData.gender === 'MALE' ? 'blue' : 'pink'}>
                    {getGenderText(profileData.gender)}
                  </Tag>
                </Descriptions.Item>
              )}
              
              {profileData.email && (
                <Descriptions.Item label="邮箱" span={1}>
                  <Space>
                    <MailOutlined />
                    {profileData.email}
                  </Space>
                </Descriptions.Item>
              )}
              
              {profileData.phone && (
                <Descriptions.Item label="电话" span={1}>
                  <Space>
                    <PhoneOutlined />
                    {profileData.phone}
                  </Space>
                </Descriptions.Item>
              )}
              
              {/* 学生特有字段 */}
              {isStudent() && (
                <>
                  {profileData.studentId && (
                    <Descriptions.Item label="学号" span={1}>
                      {profileData.studentId}
                    </Descriptions.Item>
                  )}
                  {profileData.major && (
                    <Descriptions.Item label="专业" span={1}>
                      {profileData.major}
                    </Descriptions.Item>
                  )}
                  {profileData.className && (
                    <Descriptions.Item label="班级" span={1}>
                      {profileData.className}
                    </Descriptions.Item>
                  )}
                  {profileData.enrollmentYear && (
                    <Descriptions.Item label="入学年份" span={1}>
                      {profileData.enrollmentYear}
                    </Descriptions.Item>
                  )}
                </>
              )}
              
              {/* 教师特有字段 */}
              {isTeacher() && (
                <>
                  {profileData.department && (
                    <Descriptions.Item label="院系" span={1}>
                      {profileData.department}
                    </Descriptions.Item>
                  )}
                  {profileData.title && (
                    <Descriptions.Item label="职称" span={1}>
                      <Tag color="blue">{profileData.title}</Tag>
                    </Descriptions.Item>
                  )}
                  {profileData.hireDate && (
                    <Descriptions.Item label="入职时间" span={1}>
                      {moment(profileData.hireDate).format('YYYY-MM-DD')}
                    </Descriptions.Item>
                  )}
                </>
              )}
              
              {profileData.birthDate && (
                <Descriptions.Item label="出生日期" span={1}>
                  {moment(profileData.birthDate).format('YYYY-MM-DD')}
                </Descriptions.Item>
              )}
              
              {profileData.address && (
                <Descriptions.Item label="地址" span={2}>
                  <Space>
                    <HomeOutlined />
                    {profileData.address}
                  </Space>
                </Descriptions.Item>
              )}
              
              {profileData.bio && (
                <Descriptions.Item label="个人简介" span={2}>
                  {profileData.bio}
                </Descriptions.Item>
              )}
            </Descriptions>
          </TabPane>
          
          {/* 学生的最近预订 */}
          {isStudent() && (
            <TabPane tab="最近预订" key="2">
              {recentBookings.length > 0 ? (
                <div>
                  {recentBookings.map(booking => (
                    <Card
                      key={booking.id}
                      size="small"
                      style={{ marginBottom: 8 }}
                      title={booking.course.name}
                      extra={
                        <Tag color={getStatusColor(booking.status)}>
                          {getStatusText(booking.status)}
                        </Tag>
                      }
                    >
                      <p>课程代码: {booking.course.code}</p>
                      <p>教师: {booking.course.teacher.name}</p>
                      <p>预订时间: {moment(booking.createdAt).format('YYYY-MM-DD HH:mm')}</p>
                    </Card>
                  ))}
                </div>
              ) : (
                <div style={{ textAlign: 'center', padding: '50px' }}>
                  <BookOutlined style={{ fontSize: '48px', color: '#ccc' }} />
                  <p>暂无预订记录</p>
                </div>
              )}
            </TabPane>
          )}
          
          {/* 教师的最近课程 */}
          {isTeacher() && (
            <TabPane tab="我的课程" key="2">
              {recentCourses.length > 0 ? (
                <div>
                  {recentCourses.map(course => (
                    <Card
                      key={course.id}
                      size="small"
                      style={{ marginBottom: 8 }}
                      title={course.name}
                      extra={
                        <Tag color={course.status === 'OPEN' ? 'green' : course.status === 'FULL' ? 'orange' : 'red'}>
                          {course.status === 'OPEN' ? '开放' : course.status === 'FULL' ? '已满' : '关闭'}
                        </Tag>
                      }
                    >
                      <p>课程代码: {course.code}</p>
                      <p>学分: {course.credit} | 学时: {course.hours}</p>
                      <p>地点: {course.location}</p>
                      <p>时间: {moment(course.startTime).format('YYYY-MM-DD HH:mm')} - {moment(course.endTime).format('YYYY-MM-DD HH:mm')}</p>
                    </Card>
                  ))}
                </div>
              ) : (
                <div style={{ textAlign: 'center', padding: '50px' }}>
                  <BookOutlined style={{ fontSize: '48px', color: '#ccc' }} />
                  <p>暂无课程</p>
                </div>
              )}
            </TabPane>
          )}
        </Tabs>
      </Card>

      {/* 编辑资料模态框 */}
      <Modal
        title="编辑个人资料"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleUpdateProfile}
        >
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: '请输入姓名' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="gender"
            label="性别"
            rules={[{ required: true, message: '请选择性别' }]}
          >
            <Select placeholder="选择性别">
              <Option value="MALE">男</Option>
              <Option value="FEMALE">女</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="phone"
            label="电话"
          >
            <Input />
          </Form.Item>

          {/* 学生特有字段 */}
          {isStudent() && (
            <>
              <Form.Item
                name="studentId"
                label="学号"
                rules={[{ required: true, message: '请输入学号' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name="major"
                label="专业"
                rules={[{ required: true, message: '请输入专业' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name="className"
                label="班级"
                rules={[{ required: true, message: '请输入班级' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name="enrollmentYear"
                label="入学年份"
                rules={[{ required: true, message: '请输入入学年份' }]}
              >
                <InputNumber
                  min={1900}
                  max={new Date().getFullYear()}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </>
          )}

          {/* 教师特有字段 */}
          {isTeacher() && (
            <>
              <Form.Item
                name="department"
                label="院系"
                rules={[{ required: true, message: '请输入院系' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                name="title"
                label="职称"
                rules={[{ required: true, message: '请选择职称' }]}
              >
                <Select placeholder="选择职称">
                  <Option value="教授">教授</Option>
                  <Option value="副教授">副教授</Option>
                  <Option value="讲师">讲师</Option>
                  <Option value="助教">助教</Option>
                </Select>
              </Form.Item>
              <Form.Item
                name="hireDate"
                label="入职时间"
              >
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item
                name="bio"
                label="个人简介"
              >
                <Input.TextArea rows={3} />
              </Form.Item>
            </>
          )}

          <Form.Item
            name="birthDate"
            label="出生日期"
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="address"
            label="地址"
          >
            <Input.TextArea rows={2} />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                更新
              </Button>
              <Button onClick={() => setEditModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改密码模态框 */}
      <Modal
        title="修改密码"
        open={passwordModalVisible}
        onCancel={() => setPasswordModalVisible(false)}
        footer={null}
        width={400}
      >
        <Form
          form={passwordForm}
          layout="vertical"
          onFinish={handleChangePassword}
        >
          <Form.Item
            name="currentPassword"
            label="当前密码"
            rules={[{ required: true, message: '请输入当前密码' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码至少6位' }
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            label="确认新密码"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'));
                }
              })
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                修改密码
              </Button>
              <Button onClick={() => setPasswordModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Profile;